package cn.com.wf.action;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.workflow.util.JsonUtils;
/**
 * 流程模型控制器
 */
@Controller
@RequestMapping(value = "/wf/user")
public class UserWFAction {

    @Autowired
    private IdentityService identityService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    
    /**
     * 启动流程
     * @param pid 流程key
     * @param userId 启动用户id
     * @return
     */
    @RequestMapping(value = "start")
    @ResponseBody
    public String startWorkflow(String pdKey, String userId) {
    	 ProcessInstance processInstance = null;
    	 Map<String, Object> variables = new HashMap<String, Object>();
         try {
             // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
             identityService.setAuthenticatedUserId(userId);

             processInstance = runtimeService.startProcessInstanceByKey(pdKey, userId, variables);
         } finally {
             identityService.setAuthenticatedUserId(null);
         }
 		Map<String, String> param = new HashMap<String, String>();
 		param.put("pid", processInstance.getId());
         return JsonUtils.ToJson(param);
    }
    
    /**
     * 签收任务
     */
    @RequestMapping(value = "claim")
    @ResponseBody
    public String claim(String taskId, String userId) {
        taskService.claim(taskId, userId);
        return "ok";
    }
    
    /**
     * 完成任务
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "complete")
    @ResponseBody
    public String complete(String taskId) {
        try {
       	 	Map<String, Object> variables = new HashMap<String, Object>();
            taskService.complete(taskId, variables);
            return "success";
        } catch (Exception e) {
        	e.printStackTrace();
            return "error";
        }
    }
    
    @RequestMapping(value = "claimComplete")
    @ResponseBody
    public String claimComplete(String taskId, String userId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
       	 	Map<String, Object> variables = new HashMap<String, Object>();
            taskService.claim(taskId, userId);
            taskService.complete(taskId, variables);
            resultMap.put("status", "success");
        } catch (Exception e) {
        	e.printStackTrace();
            resultMap.put("status", "error");
        }
        return JsonUtils.ToJson(resultMap);
    }
    
    /**
     * 查询待办任务
     */
    @RequestMapping(value = "todu")
    @ResponseBody
    public String TodoTasks(String userId) {
        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId);
        List<Task> tasks = taskQuery.list();
        Map<String, String> map = new HashMap<String, String>();
        for(Task t : tasks){
        	map.put(t.getProcessInstanceId(), t.getId());
        }
        return JsonUtils.ToJson(map);
    }
    
    /**
     * 得到可用流程
     */
    @RequestMapping(value = "wflist")
    @ResponseBody
    public String getProcessList() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().active().orderByDeploymentId().desc();
        List<ProcessDefinition> list = query.list();
        Map<String, String> map = new HashMap<String, String>();
        for(ProcessDefinition pd : list){
        	map.put(pd.getKey(), pd.getName());
            
        }
        return URLEncoder.encode(JsonUtils.ToJson(map));
    }
    

}
